﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using System.Collections.Specialized;

namespace BaseTypesControlLib.Controls
{
    public class ObjectChoiceControl:ChoiceFieldControl
    {

        static ObjectChoiceControl()
        {
            FrameworkPropertyMetadata fpm = new FrameworkPropertyMetadata(null,
                FrameworkPropertyMetadataOptions.AffectsArrange |
                FrameworkPropertyMetadataOptions.AffectsMeasure, OnChoicesPropertyChanged);
            ChoicesProperty = DependencyProperty.Register("Choices", typeof(ObservableCollection<string>), 
                typeof(ObjectChoiceControl), fpm);
        }

        public ObservableCollection<string> Choices
        {
            get { return (ObservableCollection<string>)GetValue(ChoicesProperty); }
            set { SetValue(ChoicesProperty, value); }
        }
        public static readonly DependencyProperty ChoicesProperty;

        private static void OnChoicesPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ObjectChoiceControl ctrl = o as ObjectChoiceControl;
            if (ctrl != null)
            {
                ctrl.CollectionChanged((ObservableCollection<string>)e.OldValue, 
                    (ObservableCollection<string>)e.NewValue);
            }
        }
        protected void CollectionChanged(ObservableCollection<string> oldCol, ObservableCollection<string> newCol)
        {
            if (oldCol != null)
                oldCol.CollectionChanged -= col_CollectionChanged;
            if (newCol != null)
                Choices.CollectionChanged += col_CollectionChanged;
            UpdateText();
        }


        private void col_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            UpdateText();
        }
        protected override void UpdateText()
        {
            if (SelectedIndex >= 0 && SelectedIndex < Choices.Count)
            {
                txtText.Text = Choices[SelectedIndex];
            }
            else
            {
                txtText.Text = "";
            }
        }

    }
}
